
import { ProTable } from '@ant-design/pro-table'
import { useAxiosGet, useAxiosWebPost, useModel, useModelTable } from '@sker/sdk'
import { SysSetting } from '@sker/model'
import { AddonMenuSelector, AddonMenuSelectorButton, AttachmentSelectModal, NgerEditor, TmapInput, renderAdminPage } from '@sker/ui'
import { PageContainer } from '@ant-design/pro-layout'
import { BetaSchemaForm } from '@ant-design/pro-form'
import { Button, Form, Popconfirm } from 'antd'
import { useEffect, useRef } from 'react'
import { ActionType } from '@ant-design/pro-components'

export const Setting: React.FC<{}> = ({ }) => {
    return <PageContainer
        className='bg-white'
        title="全局系统参数设置"
        subTitle="系统配置项目，负责系统运行基础参数配置，请在技术人员指导下添加或修改"
        tabList={[{
            tab: '基本信息',
            tabKey: 'BaseSetting',
            children: <BaseSetting />
        }, {
            tab: '备案执照',
            tabKey: 'ICPSSetting',
            children: <ICPSSetting />
        }, {
            tab: 'SEO设置',
            tabKey: 'SeoSetting',
            children: <SeoSetting />
        }, {
            tab: '关于我们',
            tabKey: 'AboutUsSetting',
            children: <AboutUsSetting />
        }, {
            tab: '注册短信配置',
            tabKey: 'SmsSetting',
            children: <SmsSetting />
        }, {
            tab: '邮箱配置',
            tabKey: 'EmailSetting',
            children: <EmailSetting />
        }, {
            tab: '系统参数列表',
            tabKey: 'setting-list',
            children: <SettingList />
        }, {
            tab: '添加参数配置',
            tabKey: 'setting-add',
            children: <SettingAdd />
        },]}
    >
    </PageContainer>
}

renderAdminPage(Setting, 'imeepos/core/web/setting')

export const EmailSetting: React.FC<{}> = ({ }) => {
    const { fetch: getSetting, data } = useAxiosWebPost('imeepos/core/system/setting/getSetting')
    const { fetch: saveSetting } = useAxiosWebPost('imeepos/core/system/setting/saveSetting')
    const [form] = Form.useForm()
    useEffect(() => {
        form.setFieldsValue(data)
    }, [data])
    useEffect(() => {
        getSetting({ key: 'pc.email' })
    }, [])
    return <BetaSchemaForm
        form={form}
        onFinish={async (values) => {
            await saveSetting({ key: 'pc.email', value: values })
        }}
        columns={[
            { title: '主机', dataIndex: 'host' },
            { title: '端口号', dataIndex: 'port' },
            { title: '用户名', dataIndex: 'username' },
            { title: '密码', dataIndex: 'password' },
            { title: '注册模板', dataIndex: 'register', valueType: 'textarea', tooltip: '变量为:{{code}}' },
            { title: '找回密码模板', dataIndex: 'forget', valueType: 'textarea', tooltip: '变量为:{{code}}' },
        ]}
    />
}

export const SmsSetting: React.FC<{}> = ({ }) => {
    const { fetch: getSetting, data } = useAxiosWebPost('imeepos/core/system/setting/getSetting')
    const { fetch: saveSetting } = useAxiosWebPost('imeepos/core/system/setting/saveSetting')
    const [form] = Form.useForm()
    useEffect(() => {
        form.setFieldsValue(data)
    }, [data])
    useEffect(() => {
        getSetting({ key: 'pc.sms' })
    }, [])
    return <BetaSchemaForm
        form={form}
        onFinish={async (values) => {
            await saveSetting({ key: 'pc.sms', value: values })
        }}
        columns={[
            { title: 'AccesskeyId', dataIndex: 'accesskeyId' },
            { title: 'AccesskeySecret', dataIndex: 'accesskeySecret' },
            { title: '域名', dataIndex: 'domain', tooltip: '如: dysmsapi.aliyuncs.com' },
            { title: 'Region', dataIndex: 'region', tooltip: '如：ch-hangzhou' },
            { title: '模板编号', dataIndex: 'templatecode', tooltip: '如：SMS_xxx，模板变量为code' },
        ]}
    />
}

export const AboutUsSetting: React.FC<{}> = ({ }) => {
    const { fetch: getSetting, data } = useAxiosWebPost('imeepos/core/system/setting/getSetting')
    const { fetch: saveSetting } = useAxiosWebPost('imeepos/core/system/setting/saveSetting')
    const [form] = Form.useForm()
    useEffect(() => {
        form.setFieldsValue(data)
    }, [data])
    useEffect(() => {
        getSetting({ key: 'pc.aboutus' })
    }, [])
    return <BetaSchemaForm form={form} onFinish={async (values) => {
        await saveSetting({ key: 'pc.aboutus', value: values })
    }} columns={[
        { title: '企业名称', dataIndex: 'title' },
        {
            title: '企业LOGO', dataIndex: 'logo', renderFormItem: (schema, config, form, action) => {
                const value = form.getFieldValue('logo')
                const values = [];
                if (value) {
                    values.push(value)
                }
                return <AttachmentSelectModal multi={false} value={values} onSelect={e => {
                    form.setFieldValue('logo', e)
                }} />
            }
        },
        { title: '联系邮箱', dataIndex: 'email' },
        { title: '客服电话', dataIndex: 'phone' },
        {
            title: '联系地址', dataIndex: 'address', renderFormItem(schema, config, form, action) {
                const value = form.getFieldValue('address')
                return <TmapInput value={value} onChange={e => {
                    form.setFieldValue('address', e.address)
                    form.setFieldValue('latlng', `${e.location.lat},${e.location.lng}`)
                }} />
            },
        },
        { title: '经纬度', dataIndex: 'latlng', formItemProps: { hidden: true } },
        { title: '介绍一下吧', dataIndex: 'desc', valueType: 'textarea' },
        {
            title: '详情', dataIndex: 'content', renderFormItem: (schema, config, form, action) => {
                const html = form.getFieldValue('content')
                return <NgerEditor html={html} onChange={e => {
                    form.setFieldValue('content', e)
                }} />
            }
        }
    ]} />
}

export const SeoSetting: React.FC<{}> = () => {
    const { fetch: getSetting, data } = useAxiosWebPost('imeepos/core/system/setting/getSetting')
    const { fetch: saveSetting } = useAxiosWebPost('imeepos/core/system/setting/saveSetting')
    const [form] = Form.useForm()
    useEffect(() => {
        form.setFieldsValue(data)
    }, [data])
    useEffect(() => {
        getSetting({ key: 'pc.seo' })
    }, [])
    return <BetaSchemaForm form={form} onFinish={async (values) => {
        await saveSetting({ key: 'pc.seo', value: values })
    }} columns={[
        { title: '站点名称', dataIndex: 'title' },
        { title: '站点简介', dataIndex: 'desc', valueType: 'textarea' },
        { title: '关键字', dataIndex: 'keyword', valueType: 'textarea' },
    ]} />
}

export const ICPSSetting: React.FC<{}> = () => {
    const { fetch: getSetting, data } = useAxiosWebPost('imeepos/core/system/setting/getSetting')
    const { fetch: saveSetting } = useAxiosWebPost('imeepos/core/system/setting/saveSetting')
    const [form] = Form.useForm()
    useEffect(() => {
        form.setFieldsValue(data)
    }, [data])
    useEffect(() => {
        getSetting({ key: 'pc.ipc' })
    }, [])
    return <BetaSchemaForm form={form} onFinish={async (values) => {
        await saveSetting({ key: 'pc.ipc', value: values })
    }} columns={[

        { title: '备案号', dataIndex: 'title', tooltip: '如：京ICP备11041704号' },
        { title: '跳转连接', dataIndex: 'url', tooltip: `如：http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=xxxx` }
    ]} />
}

export const BaseSetting: React.FC<{}> = ({ }) => {
    const { fetch: getSetting, data } = useAxiosWebPost('imeepos/core/system/setting/getSetting')
    const { fetch: saveSetting } = useAxiosWebPost('imeepos/core/system/setting/saveSetting')
    const [form] = Form.useForm()
    useEffect(() => {
        form.setFieldsValue(data)
    }, [data])
    useEffect(() => {
        getSetting({ key: 'pc.base' })
    }, [])
    return <BetaSchemaForm
        form={form}
        onFinish={async (values) => {
            await saveSetting({ key: 'pc.base', value: values })
        }}
        columns={[
            { title: '关闭站点', dataIndex: 'status', valueType: 'switch' },
            {
                valueType: 'dependency', name: ['status'], columns: ({ status }) => {
                    if (status) {
                        return [
                            { title: '关闭原因', valueType: 'textarea' },
                        ]
                    }
                    return [

                        {
                            title: 'PC首页', dataIndex: 'home', renderFormItem: (schema, config, form, action) => {
                                const value = form.getFieldValue('home')
                                return <AddonMenuSelectorButton value={value} onChange={(link, main, title, name) => {
                                    form.setFieldValue('home', link)
                                }} />
                            }
                        },
                        {
                            title: '默认登陆', dataIndex: 'login', renderFormItem: (schema, config, form, action) => {
                                const value = form.getFieldValue('login')
                                return <AddonMenuSelectorButton value={value} onChange={(link, main, title, name) => {
                                    form.setFieldValue('login', link)
                                }} />
                            }
                        },
                    ]
                }
            },
        ]} />
}

export const SettingAdd: React.FC<{}> = ({ }) => {
    return <BetaSchemaForm columns={[
        { title: '配置代号', fieldProps: { formItemProps: [{ required: true, message: '配置代号必填' }] }, tooltip: '唯一键' },
        { title: '备注', valueType: 'textarea', tooltip: '备注备忘，方便查找记忆' },
        { title: '配置项目', valueType: 'jsonCode', tooltip: '请输入json格式的内容', formItemProps: { rules: [{ required: true, message: '配置项目必填' }] } }
    ]} />
}

const SettingList: React.FC<{}> = ({ }) => {
    const model = useModel(SysSetting)
    const actionRef = useRef<ActionType>()
    return <ProTable
        rowKey={'code'}
        tableExtraRender={() => {
            return <></>
        }}
        request={async (params) => {
            return model.find(['code', 'desc', 'data'])
        }}
        search={false}
        toolBarRender={false}
        actionRef={actionRef}
        columns={[
            { title: '配置代号', dataIndex: 'code' },
            { title: '备注', dataIndex: 'desc' },
            {
                title: '项目', dataIndex: 'data', renderText(text, record, index, action) {
                    return <pre>{JSON.stringify(text, null, 2)}</pre>
                },
            },
            {
                title: '操作', align: 'right',
                renderText(text, record, index, action) {
                    return <>
                        <Popconfirm onConfirm={async e => {
                            await model.delete(record.code)
                            await actionRef.current?.reload();
                        }} title={'此操作不可逆!您确定要执行此操作吗？'} description={'删除后无法恢复，请慎重操作！！'}>
                            <Button size={'small'} type={'link'} danger>删除</Button>
                        </Popconfirm>
                    </>
                },
            }
        ]}
    />
}